package lab2Exercise2;

public class ArrayQueue<E> implements Queue<E> {
	private int f; // front of queue
	private int r; // rear of queue
	private int capacity;
    private E[] Q;
    private static int MAX = 100; 

    public ArrayQueue(int capacity){
       this.capacity = capacity;
       Q = (E[]) new Object[capacity];
       f = 0;
       r = 0;
    } 

    public ArrayQueue(){
       this(MAX);
    }

    public int size(){
        return (Q.length - f + r) % capacity;
    }
    public boolean isEmpty(){
        return (f==r);
    }

    public E front() throws QueueException {
        if (isEmpty())
           throw new QueueException("Queue is empty.");
        return Q[f];
     }

    public E dequeue() throws QueueException {
        if (isEmpty())
          throw new QueueException("Queue is empty.");
        E tmp = Q[f];
        Q[f] = null;
        f = (f+1) % capacity;
        return tmp;
    }
    
    public void enqueue(E e) throws QueueException {
        if (size() == capacity - 1)
          throw new QueueException("Queue is full.");
        Q[r] = e;
        r = (r+1) % capacity;
    }
    
    public String toString()
    {
    	StringBuffer buff = new StringBuffer("[");
    	
    	for(int i = 0; i < size(); i++) {
    		if((i+1) == r) {
    			buff.append(Q[(f+i)%capacity]);
    		} else {
    			buff.append(Q[(f+i)%capacity] + ",");
    		}
    		 
    	}
    	buff.append("]");
    	return buff.toString();
    }
}
